<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{

    private $user;
    private $userdata;
    private $username;
    private $email;
    private $phone;
    private $password;

    public function __construct(Request $request)
    {
        $this->user = new User();
        $this->userdata = $request->all();
        $this->username = $request->username;
        $this->email = $request->email;
        $this->phone = $request->phone;
        $this->password = Hash::make($request->password);
    }

    // 注册
    public function register(Request $request){

        $validator =  Validator::make($this->userdata,[
            'email' => 'required|email:rfc,dns|unique:App\Models\User,email',
            'username' => 'required|alpha_dash|min:6|unique:App\Models\User,name',
            'password' => 'required|min:6',
            'ConfirmPassword' => 'same:password'
        ]);

        if($validator->fails()){
            $error_str = [];

            foreach ($validator->errors()->toarray() as $v) {
                $error_str[] = $v[0];
            }
            return $this->ReturnError('registration failed', ['error' => $error_str[0]]);
        }

        $this->user->email = $this->email;
        $this->user->password = $this->password;
        $this->user->name = $this->username;
        $user = $this->user->save();

        return $this->ReturnSuccess('registration success');
        
    }

    // 登录
    public function login(){

// dd(Session::all());

        $user = $this->user->where('name', $this->username)->first();
        if(!$user){
            $user = $this->user->where('email', $this->username)->first();
        }

        if(!$user){
            return $this->ReturnError('Login failed', ['error' => 'Invalid username']);
        }

        if(Hash::check($this->userdata['password'], $user->password)){

            Session::put([
                'uid' =>  $user->id,
                'username' =>  $user->name,
                'email' =>  $user->email
            ]);
            Session::save();

            return $this->ReturnSuccess('Login success');
        }else{
            return $this->ReturnError('Login failed', ['error' => 'wrong password']);
        }
    }

        // 退出登录

        public function logout(){

            Session::remove('uid');
            Session::remove('username');
            Session::remove('email');

            return $this->ReturnSuccess('logout success');
        }

}


